using Windows.System;

namespace MultiAgentsClient.Behaviors;

public class CommandOnKeyPressBehavior
{
    public static object GetCommandParameter(DependencyObject dependencyObject)
    {
        return dependencyObject.GetValue(CommandParameterProperty);
    }

    public static ICommand GetTextBoxCommand(DependencyObject dependencyObject)
    {
        return (ICommand)dependencyObject.GetValue(TextBoxCommandProperty);
    }

    public static void SetCommandParameter(DependencyObject dependencyObject, object value)
    {
        dependencyObject.SetValue(CommandParameterProperty, value);
    }

    public static void SetTextBoxCommand(DependencyObject dependencyObject, ICommand value)
    {
        dependencyObject.SetValue(TextBoxCommandProperty, value);
    }

    public static readonly DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached(
            "CommandParameter",
            typeof(object),
            typeof(CommandOnKeyPressBehavior),
            new PropertyMetadata(null));

    public static readonly DependencyProperty TextBoxCommandProperty =
        DependencyProperty.RegisterAttached(
            "TextBoxCommand",
            typeof(ICommand),
            typeof(CommandOnKeyPressBehavior),
            new PropertyMetadata(default(ICommand), OnTextBoxCommandChanged));

    private static void OnTextBoxCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is TextBox textBox)
        {
            textBox.KeyDown -= TextBoxKeyDownHandler;

            textBox.KeyDown += TextBoxKeyDownHandler;
        }
    }

    private static void TextBoxKeyDownHandler(object sender, Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e)
    {
        if (e.Key == VirtualKey.Enter)
        {
            if (sender is not TextBox textBox)
            {
                return;
            }

            ICommand command = GetTextBoxCommand(textBox);
            object parameter = GetCommandParameter(textBox);
            if (parameter != null)
            {
                command.Execute(parameter);
            }
            else
            {
                command.Execute(null);
            }
        }
    }
}
